package com.example.myapplication;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class NewsFragment extends Fragment {

    private OnNewsSelectedListener listener;

    public interface OnNewsSelectedListener {
        void onNewsSelected(int position);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);

        RecyclerView recyclerView = view.findViewById(R.id.news_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        List<News> newsList = getNewsData();
        NewsAdapter adapter = new NewsAdapter(newsList, position -> {
            if (listener != null) {
                listener.onNewsSelected(position);
            }
        });
        recyclerView.setAdapter(adapter);

        return view;
    }

    public static List<News> getNewsData() {
        List<News> newsList = new ArrayList<>();
        newsList.add(new News("新闻标题1", "新闻内容1"));
        newsList.add(new News("新闻标题2", "新闻内容2"));
        newsList.add(new News("新闻标题3", "新闻内容3"));
        return newsList;
    }

    @Override
    public void onAttach(@NonNull android.content.Context context) {
        super.onAttach(context);
        if (context instanceof OnNewsSelectedListener) {
            listener = (OnNewsSelectedListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnNewsSelectedListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }
}